package com.kaplan.hackathon;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.stream.XMLStreamException;

import net.sf.json.JSONSerializer;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONException;
import org.json.XML;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.scribe.builder.ServiceBuilder;
import org.scribe.builder.api.FacebookApi;
import org.scribe.model.OAuthRequest;
import org.scribe.model.Response;
import org.scribe.model.Token;
import org.scribe.model.Verb;
import org.scribe.model.Verifier;
import org.scribe.oauth.OAuthService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.amazonaws.util.json.JSONArray;
import com.google.gson.Gson;
import com.kaplan.hackathon.dynamodb.DynamoDBPersistence;
import com.kaplan.hackathon.models.Content;
import com.kaplan.hackathon.models.GroupPhoto;
import com.kaplan.hackathon.models.MeetupGroup;
import com.kaplan.hackathon.models.QuestionResponse;
import com.kaplan.hackathon.models.User;
import com.kaplan.hackathon.search.model.Jobs;
import com.kaplan.hackathon.search.service.FaceBookLogin;
import com.kaplan.hackathon.search.service.SearchLinkedInJobsService;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;

@Controller
@RequestMapping("/")
public class HelloController {
	private static final Log log = LogFactory.getLog(HelloController.class);
	
	private static final String NETWORK_NAME = "Facebook";
	private static final String PROTECTED_RESOURCE_URL = "https://graph.facebook.com/me";
	private static final Token EMPTY_TOKEN = null;
    String apiKey = "155986777920607";
    String apiSecret = "c9bbeede808c3f8846207f61662c9e80";
	
	@RequestMapping(method = RequestMethod.GET)
	public String printWelcome(ModelMap model) {
		//model.addAttribute("message", "Hello world!");

		OAuthService service = new ServiceBuilder()
        .provider(FacebookApi.class)
        .apiKey(apiKey)
        .apiSecret(apiSecret)
        .callback("http://careerprep.elasticbeanstalk.com/login")
        .build();
		
		model.addAttribute("url", service.getAuthorizationUrl(EMPTY_TOKEN));
		
		return "index";
	}
	
	@RequestMapping(value ="/login", method = RequestMethod.GET) 
	public String login(@RequestParam("code") String code, ModelMap moddel, HttpServletResponse res, HttpServletRequest req) {
		

	    
		  OAuthService service = new ServiceBuilder()
          .provider(FacebookApi.class)
          .apiKey(apiKey)
          .apiSecret(apiSecret)
          .callback("http://careerprep.elasticbeanstalk.com/login")
          .build();
		
		log.info(code);
		
	    Verifier verifier = new Verifier(code);
	    
	    // Trade the Request Token and Verfier for the Access Token
	    log.info("Trading the Request Token for an Access Token...");
	    Token accessToken = service.getAccessToken(EMPTY_TOKEN, verifier);
	    log.info("Got the Access Token!");
	    log.info("(if your curious it looks like this: " + accessToken + " )");

	    // Now let's go and ask for a protected resource!
	    log.info("Now we're going to access a protected resource...");
	    OAuthRequest request = new OAuthRequest(Verb.GET, PROTECTED_RESOURCE_URL);
	    service.signRequest(accessToken, request);
	    Response response = request.send();
	    log.info("Got it! Lets see what we found...");
	    
	    log.info(response.getCode());
	    //log.info(response.getBody());
	    
	    String responseBody = response.getBody();
	    Map<String, Object> responseMap = new HashMap<String, Object>();
	    
		Gson gson = new Gson();
	
		responseMap = gson.fromJson(responseBody, HashMap.class);
	    
		User user = new User();
		//user.setId(Integer.parseInt(responseMap.get("id").toString()));
		user.setUserName(responseMap.get("username").toString());
		user.setFirstName(responseMap.get("first_name").toString());
		user.setLastName(responseMap.get("last_name").toString());
		user.setFullName(user.getFirstName() + " " + user.getLastName());
		moddel.addAttribute("user", user);
		req.getSession().setAttribute("user", user);
		
	    return "dash";
	}

	@RequestMapping(value = "/meetup", method = RequestMethod.GET)
	public String home(ModelMap model, HttpServletRequest request) {
		String meetUpKey = "49285132366914506613322a363c2865";
		LearningPodService pod = new LearningPodService();
		DynamoDBPersistence db = new DynamoDBPersistence();
		//db.testCRUDOperations();
		/*
		QuestionResponse response = new QuestionResponse();
        response.setId(100001);
        response.setUuid("c0d06958-a847-4218-a32c-0ad5ebded256");
        response.setResponse("choice1");
        response.setUserId("kermit");
		db.saveResponseOperation(response);
		*/
		
		log.info("=========== " + request.getRemoteAddr());
		Client client = Client.create();
		
		String url = "https://api.meetup.com/find/groups?zip=10014&text=linux&page=20&key="+meetUpKey;
		log.info(url);
		   
    	WebResource webResoure = client.resource(url);
    	Map<String, Object> map = new HashMap<String, Object>();
    	
    	Gson gson = new Gson();
    	
    	
    	ClientResponse res = webResoure.get(ClientResponse.class);
    	String str = res.getEntity(String.class);
    	
    	
    	//log.info(map.toString());
    	Map<String, String> resMap = new HashMap<String, String>();
    	
    	//resMap = gson.fromJson(str, HashMap.class);
    	//webResoure = client.resource("https://core.learningpod.com/api/categories");
    	
    	//res = webResoure.type("application/json").header("X-Auth-Token", resMap.get("access_token")).get(ClientResponse.class);
    	
    	//log.info(str);
    	try {
			JSONArray array = new JSONArray(str);
			List<MeetupGroup> groups = new ArrayList<MeetupGroup>();
			List<GroupPhoto> photos = new ArrayList<GroupPhoto>();
			for (int i=0; i<array.length(); i++) {
				//log.info("+++++" + array.getJSONObject(i));
				net.sf.json.JSONObject json = (net.sf.json.JSONObject) JSONSerializer.toJSON(array.getJSONObject(i).toString());
				//String name = json.getString("name");
				MeetupGroup meetup = new MeetupGroup();
				meetup.setCity(json.getString("city"));
				meetup.setMembers(json.getInt("members"));
				meetup.setName(json.getString("name"));
				groups.add(meetup);
				//log.info(name);
				//model.addAttribute("group", meetup);
				
				log.info((json.getJSONObject("group_photo").toString()));
				net.sf.json.JSONObject photo = (net.sf.json.JSONObject) json.getJSONObject("group_photo");
				//model.addAttribute("photo", photo);
				
				Set<String> keySet = photo.keySet();
			    for (String key : keySet) {
			        Object value = photo.get(key);
			        System.out.printf("%s=%s (%s)\n", key, value, value.getClass()
			                .getSimpleName());
			        if (key.equalsIgnoreCase("photo_link")) {
			        	GroupPhoto p = new GroupPhoto();
			        	p.setPhoto_link(value.toString());
			        	photos.add(p);
			        	//model.addAttribute("p", p);
			        }
			       // log.info("===== " + value);
			    }
			    
				//net.sf.json.JSONObject json = (net.sf.json.JSONObject) JSONSerializer.toJSON(array.getJSONObject(i).toString());
				//model.addAttribute("photo", (json.getJSONObject("group_photo").toString()));
				
			}
			
			model.addAttribute("groups", groups);
			model.addAttribute("photos", photos);
		} catch (com.amazonaws.util.json.JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	/*
    	log.info(str.substring(1, str.length()-1));
    	str = str.substring(1, str.length()-1);
    	net.sf.json.JSONObject json = (net.sf.json.JSONObject) JSONSerializer.toJSON(str);
    	String name = json.getString("name");
    	log.info(name);
    	*/
		
		/*
		User user = new User();
		user.setFirstName("Wen");
		user.setLastName("Ye");
		user.setId(1);
		user.setUserName("wye");
		user.setLastLogin(new Date());
		
		db.saveOrUpdateUser(user);
		*/
		//Content content = pod.getQuestionByUUID("c0d06958-a847-4218-a32c-0ad5ebded256");
		//model.addAttribute("content", content);
		return "hello";
	}
	
	@RequestMapping(value = "/getMeetups", method = RequestMethod.GET)
	@ResponseBody
	public String getMeetup(String searchParam) {
		String meetUpKey = "49285132366914506613322a363c2865";
		LearningPodService pod = new LearningPodService();
		DynamoDBPersistence db = new DynamoDBPersistence();
		//db.testCRUDOperations();
		/*
		QuestionResponse response = new QuestionResponse();
        response.setId(100001);
        response.setUuid("c0d06958-a847-4218-a32c-0ad5ebded256");
        response.setResponse("choice1");
        response.setUserId("kermit");
		db.saveResponseOperation(response);
		*/
		
	//	log.info("=========== " + request.getRemoteAddr());
		Client client = Client.create();
		
		String url = "https://api.meetup.com/find/groups?zip="+searchParam+"&text=microsoft&page=20&key="+meetUpKey;
		log.info(url);
		   
    	WebResource webResoure = client.resource(url);
    	Map<String, Object> map = new HashMap<String, Object>();
    	
    	Gson gson = new Gson();
    	
    	
    	ClientResponse res = webResoure.get(ClientResponse.class);
    	String str = res.getEntity(String.class);
    	
    	
    	//log.info(map.toString());
    	Map<String, String> resMap = new HashMap<String, String>();
    	
    	//resMap = gson.fromJson(str, HashMap.class);
    	//webResoure = client.resource("https://core.learningpod.com/api/categories");
    	
    	//res = webResoure.type("application/json").header("X-Auth-Token", resMap.get("access_token")).get(ClientResponse.class);
    	
    	//log.info(str);
    	JSONArray array = null;
    	try {
			 array = new JSONArray(str);
			for (int i=0; i<array.length(); i++) {
				//log.info("+++++" + array.getJSONObject(i));
				net.sf.json.JSONObject json = (net.sf.json.JSONObject) JSONSerializer.toJSON(array.getJSONObject(i).toString());
				//String name = json.getString("name");
				MeetupGroup meetup = new MeetupGroup();
				meetup.setCity(json.getString("city"));
				meetup.setMembers(json.getInt("members"));
				meetup.setName(json.getString("name"));
				
				//log.info(name);
				//model.addAttribute("group", meetup);
				
			}
		} catch (com.amazonaws.util.json.JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	/*
    	log.info(str.substring(1, str.length()-1));
    	str = str.substring(1, str.length()-1);
    	net.sf.json.JSONObject json = (net.sf.json.JSONObject) JSONSerializer.toJSON(str);
    	String name = json.getString("name");
    	log.info(name);
    	*/
		
		/*
		User user = new User();
		user.setFirstName("Wen");
		user.setLastName("Ye");
		user.setId(1);
		user.setUserName("wye");
		user.setLastLogin(new Date());
		
		db.saveOrUpdateUser(user);
		*/
		//Content content = pod.getQuestionByUUID("c0d06958-a847-4218-a32c-0ad5ebded256");
		//model.addAttribute("content", content);
    	
    	return array.toString();
		//return "hello";
	}
	
	@RequestMapping(value = "/dash", method = RequestMethod.GET)
	public String dash() {
		return "dash";
	}

	@RequestMapping(value = "/learn", method = RequestMethod.GET)
	public String learn() {
		return "learn";
	}

	@RequestMapping(value = "/connect", method = RequestMethod.GET)
	public String connect() {
		log.info("Connect");
		return "connect";
	}

	@RequestMapping(value = "/jobs", method = RequestMethod.GET)
	public String jobs() {
		log.info("Fething Jobs");
		return "jobs";
	}

	@RequestMapping(value = "/getJobs", method = RequestMethod.GET)
	public @ResponseBody
	String getJobs(String searchParam) {
		JSONArray mJSONArray = null;
		SearchLinkedInJobsService searchLinkedInJobsService = new SearchLinkedInJobsService();
		try {
			ArrayList<Jobs> jobsList = searchLinkedInJobsService
					.searchKeywords(searchParam, "0", "20");
			if(jobsList.size() == 0)
				return "0";
			mJSONArray = new JSONArray(jobsList);

		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "0";
		} catch (XMLStreamException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "0";
		}
		return mJSONArray.toString();
	}

	@RequestMapping(value = "/searchJOB", method = RequestMethod.GET)
	public @ResponseBody
	String getJobDetails(String jobId) {
		SearchLinkedInJobsService searchLinkedInJobsService = new SearchLinkedInJobsService();
		JSONObject jsonObject = null;
		String jobsList = null;
		try {
			jobsList = searchLinkedInJobsService
					.searchJOB(jobId);
			/*try {
				//jsonObject = XML.toJSONObject(jobsList);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			*/
			

		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "0";
		} catch (XMLStreamException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "0";
		}
		if(jobsList != null)
		{	
			//System.out.println(jobsList);
			return jobsList;
		}
		else{
			return "0";
		}
	}
	
	
	
	
	@RequestMapping(value = "/video_connect", method = RequestMethod.GET)
	public String videoConnect() {
		return "video_connect";
	}

	@RequestMapping(value = "/practice", method = RequestMethod.GET)
	public String practice(ModelMap model) {
		LearningPodService pod = new LearningPodService();
		Content content = pod.getQuestionByUUID("c0d06958-a847-4218-a32c-0ad5ebded256");
	    model.addAttribute("lpContent", content);
		return "practice";
	}
	@RequestMapping(value = "/perform", method = RequestMethod.GET)
	public String perform(ModelMap model) {
		LearningPodService pod = new LearningPodService();
		Content content = pod.getQuestionByUUID("c0d06958-a847-4218-a32c-0ad5ebded256");
	    model.addAttribute("lpContent", content);
		return "practice";
	}
	@RequestMapping(value = "/getQuestion", method = RequestMethod.GET)
	public String getQuestion(String uuid,ModelMap model) {
		LearningPodService pod = new LearningPodService();
		System.out.println("UUID:"+uuid);
		Content content = pod.getQuestionByUUID(uuid);
	    model.addAttribute("lpContent", content);
		return "practice";
	}
	
	

}